package org.admanager.soa.plugin.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class ModifyXMLFile {
	public static void modify(String path) {

		try {

			SAXBuilder builder = new SAXBuilder();
			// File xmlFile = new File("c:\\file.xml");

			URL url = new URL(path);
			Document doc = (Document) builder.build(url);

			// builder.build(url)

			Element rootNode = doc.getRootElement();

			// update staff id attribute
			List<Element> component = rootNode.getContent();
			// List<Element> component = rootNode.getChildren("sca:component");

			for (Iterator iterator = component.iterator(); iterator.hasNext();) {
				Object objIter = iterator.next();
				if (objIter instanceof Element)
					if (((Element) objIter).getName().equals("component")) {
						Element element = (Element) objIter;
						String strComponentName = element.getAttribute("name")
								.getValue();
						List<Element> arrElement = element.getContent();
						// List<Element> componentService =
						// element.getChildren("sca:service");

						for (Iterator iterator2 = arrElement.iterator(); iterator2
								.hasNext();) {
							Object objIter2 = iterator2.next();
							if (objIter2 instanceof Element)
								if (((Element) objIter2).getName().equals(
										"service") || ((Element) objIter2).getName().equals("reference")) 
								{
									Element element2 = (Element) objIter2;
									String strID = strComponentName
											+ "/"
											+ element2.getAttribute("name")
													.getValue();
									// element1.add
									Attribute att = new Attribute("id", strID);
									element2.setAttribute(att);
								}
						}
					}
				/*
					else if (((Element) objIter).getName().equals("service") || ((Element) objIter).getName().equals("reference"))
					{
						Element element = (Element) objIter;
						String name = element.getAttribute("name")
								.getValue();
						Attribute att = new Attribute("id", name);
						element.setAttribute(att);
					}
				*/
			}

			XMLOutputter xmlOutput = new XMLOutputter();

			// display nice nice
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(doc, new FileWriter(url.getPath()));

		} catch (IOException io) {
			io.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}
}
